//
//  ViewController.m
//  MapDemo
//
//  Created by 王声远 on 15/8/23.
//  Copyright (c) 2015年 anody. All rights reserved.
//


#import "ViewController.h"
#import <MapKit/MapKit.h>
#import "CCLocationManager.h"

#import "BasicMapAnnotation.h"
#import "CallOutAnnotationVifew.h"
#import "JingDianMapCell.h"
#import "CalloutMapAnnotation.h"

static CGFloat mySpan = 0.00001;

@interface ViewController ()<MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (weak, nonatomic) IBOutlet UISegmentedControl *choiceView;

@property (nonatomic,assign) CLLocationCoordinate2D myCenter;

@property (nonatomic,strong) CalloutMapAnnotation *calloutAnnotation;


@property (nonatomic, retain) NSMutableArray* points;
@property (nonatomic, retain) MKPolyline* routeLine;
@property (nonatomic, retain) MKPolylineView* routeLineView;
@property (nonatomic, retain) CLLocationManager* locationManager;

@property (nonatomic,strong) CLLocation* currentLocation;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.mapView.delegate = self;
    self.mapView.showsUserLocation = YES;
    self.mapView.mapType = MKMapTypeStandard;
    self.mapView.delegate = self;
    
    CLLocationCoordinate2D coord = {28.9000, 115.22169};
    MKCoordinateSpan span = {mySpan,mySpan};
    MKCoordinateRegion region = {coord,span};
    [self.mapView setRegion:region];
    
    //[self configureRoutes];
    
    //初始化UISegmentedControl1
    [self.choiceView addTarget:self action:@selector(clickChioce:) forControlEvents:UIControlEventValueChanged];
    self.choiceView.tintColor = [UIColor redColor];
}

#pragma mark - 我的位置改变调用代理方法
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    self.myCenter = userLocation.location.coordinate;

    if (mapView.tag == 1) {
        CLLocationCoordinate2D coord2D = userLocation.location.coordinate;//显示范围精度
        MKCoordinateSpan span = {mySpan,mySpan};//显示区域
        MKCoordinateRegion region = {coord2D,span};//设置显示区域
        [mapView setRegion:region animated:NO];
        mapView.tag = 0;
    }
    
    //以下代码把我的位置放到数组里
    CLLocation *location = [[CLLocation alloc] initWithLatitude:userLocation.coordinate.latitude
                                                      longitude:userLocation.coordinate.longitude];
    if  (userLocation.coordinate.latitude == 0.0f ||
         userLocation.coordinate.longitude == 0.0f)
        return;
    
    // check the move distance
    if (_points.count > 0)
    {
        CLLocationDistance distance = [location distanceFromLocation:_currentLocation];
        NSLog(@"distance: %f",distance);
        if (distance < 5)
            return;
    }
    
    if (nil == _points) {
        _points = [[NSMutableArray alloc] init];
    }
    
    [_points addObject:location];
    _currentLocation = location;
    
    NSLog(@"points: %@", _points);
    
    [self configureRoutes];
    
    //把我的位置放在中间
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(userLocation.coordinate.latitude, userLocation.coordinate.longitude);
    [self.mapView setCenterCoordinate:coordinate animated:YES];
}

#pragma mark - SegmentedControl点击事件
- (void)clickChioce:(UISegmentedControl *)segment
{
    if(segment.selectedSegmentIndex == 0){//平面图
        self.mapView.mapType = MKMapTypeStandard;
    }
    else if(segment.selectedSegmentIndex == 1)//卫星图
    {
        self.mapView.mapType = MKMapTypeHybrid;
    }
    else if(segment.selectedSegmentIndex == 2){//我的位置
        MKCoordinateSpan span = {mySpan,mySpan};
        MKCoordinateRegion region = {self.myCenter,span};
        [self.mapView setRegion:region animated:YES];
    }
    else if(segment.selectedSegmentIndex == 3){//地图标识
        NSLog(@"地图标识");
        [self addAnnotions:self.myCenter];
    }
    else if(segment.selectedSegmentIndex == 4)//移动轨迹
    {
        NSLog(@"移动轨迹");
    }
}

#pragma mark - 添加地址标识(大头钉)
-(void)addAnnotions:(CLLocationCoordinate2D)center
{
    CLLocationCoordinate2D temp = center;
    NSLog(@"center: %f -> %f",center.latitude,center.longitude);//22.506734 -> 114.061045
    
    center.latitude = center.latitude + 0.0003;
    center.longitude = center.longitude + 0.0003;
    NSDictionary *dic1=[NSDictionary dictionaryWithObjectsAndKeys:@(center.latitude),@"latitude",@(center.longitude),@"longitude",nil];
    
    center = temp;
    center.latitude = center.latitude + 0.0002;
    center.longitude = center.longitude - 0.0004;
    NSDictionary *dic2=[NSDictionary dictionaryWithObjectsAndKeys:@(center.latitude),@"latitude",@(center.longitude),@"longitude",nil];
    
    center = temp;
    center.latitude = center.latitude + 0.0001;
    center.longitude = center.longitude + 0.0001;
    NSDictionary *dic3=[NSDictionary dictionaryWithObjectsAndKeys:@(center.latitude),@"latitude",@(center.longitude),@"longitude",nil];

    center = temp;
    center.latitude = center.latitude - 0.0004;
    center.longitude = center.longitude - 0.0004;
    NSDictionary *dic4=[NSDictionary dictionaryWithObjectsAndKeys:@(center.latitude),@"latitude",@(center.longitude),@"longitude",nil];
    
    NSArray *array = [NSArray arrayWithObjects:dic1,dic2,dic3,dic4, nil];
    
    for (NSDictionary *dic in array) {
        
        CLLocationDegrees latitude=[[dic objectForKey:@"latitude"] doubleValue];
        CLLocationDegrees longitude=[[dic objectForKey:@"longitude"] doubleValue];
        CLLocationCoordinate2D location=CLLocationCoordinate2DMake(latitude, longitude);
        
        MKCoordinateRegion region=MKCoordinateRegionMakeWithDistance(location,mySpan ,mySpan );
        MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:region];
        [_mapView setRegion:adjustedRegion animated:YES];
        
        BasicMapAnnotation *  annotation=[[BasicMapAnnotation alloc] initWithLatitude:latitude andLongitude:longitude];
        [_mapView   addAnnotation:annotation];
    }
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    
    NSLog(@"%@",[annotation class]);
    
    if ([annotation isKindOfClass:[CalloutMapAnnotation class]]) {
        
        CallOutAnnotationVifew *annotationView = (CallOutAnnotationVifew *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"CalloutView"];
        if (!annotationView) {
            annotationView = [[CallOutAnnotationVifew alloc] initWithAnnotation:annotation reuseIdentifier:@"CalloutView"];
            JingDianMapCell  *cell = [[[NSBundle mainBundle] loadNibNamed:@"JingDianMapCell" owner:self options:nil] objectAtIndex:0];
            [annotationView.contentView addSubview:cell];
            
        }
        return annotationView;
    }
    
    //地址标识(图片)
    else if ([annotation isKindOfClass:[BasicMapAnnotation class]]) {
        MKAnnotationView *annotationView =[self.mapView dequeueReusableAnnotationViewWithIdentifier:@"CustomAnnotation"];
        if (!annotationView) {
            annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation
                                                           reuseIdentifier:@"CustomAnnotation"];
            annotationView.canShowCallout = NO;
            annotationView.image = [UIImage imageNamed:@"pin.png"];
        }
        return annotationView;
    }
    
    //我的位置
    else if ([annotation isKindOfClass:[MKUserLocation class]]){
        NSLog(@"我的位置");
    }
    
    return nil;
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
    
    if ([view.annotation isKindOfClass:[BasicMapAnnotation class]])
    {
        if (_calloutAnnotation.coordinate.latitude == view.annotation.coordinate.latitude&&
            _calloutAnnotation.coordinate.longitude == view.annotation.coordinate.longitude) {
            return;
        }
        if (_calloutAnnotation) {
            [mapView removeAnnotation:_calloutAnnotation];
            _calloutAnnotation = nil;
        }
        _calloutAnnotation = [[CalloutMapAnnotation alloc]
                               initWithLatitude:view.annotation.coordinate.latitude
                               andLongitude:view.annotation.coordinate.longitude];
        [mapView addAnnotation:_calloutAnnotation];
        
        [mapView setCenterCoordinate:_calloutAnnotation.coordinate animated:YES];
        
    }
    else
    {
        NSLog(@"click");
    }
}

- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view {
    if (_calloutAnnotation&& ![view isKindOfClass:[CallOutAnnotationVifew class]]) {
        if (_calloutAnnotation.coordinate.latitude == view.annotation.coordinate.latitude&&
            _calloutAnnotation.coordinate.longitude == view.annotation.coordinate.longitude) {
            [mapView removeAnnotation:_calloutAnnotation];
            _calloutAnnotation = nil;
        }
    }
}

#pragma mark - 获取当前位置信息
//- (void)getCurrentLocation
//{
//    __block NSString *string;
//    
//    [[CCLocationManager shareLocation]getLocationCoordinate:^(CLLocationCoordinate2D locationCorrrdinate) {
//        
//        string = [NSString stringWithFormat:@"%f %f",locationCorrrdinate.latitude,locationCorrrdinate.longitude];
//        NSLog(@"纬度：%@",string);
//        
//        CLLocationCoordinate2D coord = {locationCorrrdinate.latitude, locationCorrrdinate.longitude};
//        MKCoordinateSpan span = {0.01,0.01};
//        
//        MKCoordinateRegion region = {coord,span};
//        
//        [self.mapView setRegion:region];
//        
//    } withAddress:^(NSString *addressString) {
//        
//        NSLog(@"%@",addressString);
//        string = [NSString stringWithFormat:@"%@ > %@",string,addressString];
//        NSLog(@"您的当前位置是:%@",string);
//        
//    }];
//}

- (void)configureRoutes
{
    // define minimum, maximum points
    MKMapPoint northEastPoint = MKMapPointMake(0.f, 0.f);
    MKMapPoint southWestPoint = MKMapPointMake(0.f, 0.f);
    
    // create a c array of points.
    MKMapPoint* pointArray = malloc(sizeof(CLLocationCoordinate2D) * _points.count);
    
    // for(int idx = 0; idx < pointStrings.count; idx++)
    for(int idx = 0; idx < _points.count; idx++)
    {
        CLLocation *location = [_points objectAtIndex:idx];
        CLLocationDegrees latitude  = location.coordinate.latitude;
        CLLocationDegrees longitude = location.coordinate.longitude;
        
        // create our coordinate and add it to the correct spot in the array
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
        MKMapPoint point = MKMapPointForCoordinate(coordinate);
        
        // if it is the first point, just use them, since we have nothing to compare to yet.
        if (idx == 0) {
            northEastPoint = point;
            southWestPoint = point;
        } else {
            if (point.x > northEastPoint.x)
                northEastPoint.x = point.x;
            if(point.y > northEastPoint.y)
                northEastPoint.y = point.y;
            if (point.x < southWestPoint.x)
                southWestPoint.x = point.x;
            if (point.y < southWestPoint.y)
                southWestPoint.y = point.y;
        }
        
        pointArray[idx] = point;
    }
    
    if (self.routeLine) {
        [self.mapView removeOverlay:self.routeLine];
    }
    
    self.routeLine = [MKPolyline polylineWithPoints:pointArray count:_points.count];
    
    // add the overlay to the map
    if (nil != self.routeLine) {
        [self.mapView addOverlay:self.routeLine];
    }
    
    // clear the memory allocated earlier for the points
    free(pointArray);
}

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
    MKOverlayView* overlayView = nil;
    
    NSLog(@"routeLineView");
    
    if(overlay == self.routeLine)
    {
        //if we have not yet created an overlay view for this overlay, create it now.
        if (self.routeLineView) {
            [self.routeLineView removeFromSuperview];
        }
        
        self.routeLineView = [[MKPolylineView alloc] initWithPolyline:self.routeLine];
        self.routeLineView.fillColor = [UIColor redColor];
        self.routeLineView.strokeColor = [UIColor redColor];
        self.routeLineView.lineWidth = 10;
        
        overlayView = self.routeLineView;
    }
    
    return overlayView;
}

@end
